package com.farm.wcp.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.farm.authority.service.OutuserServiceInter;
import com.farm.authority.service.UserServiceInter;
import com.farm.cbtg.domain.ex.CatalogDomain;
import com.farm.configer.domain.Configer;
import com.farm.configer.domain.Configerform;
import com.farm.configer.domain.ex.ConfigerMetaPara;
import com.farm.configer.form.ConfigerFormGenerator;
import com.farm.configer.form.FormModel;
import com.farm.configer.form.FormModelUtils;
import com.farm.configer.service.ConfigerServiceInter;
import com.farm.core.page.ViewMode;
import com.farm.project.service.ProjectServiceInter;
import com.farm.sfile.WdapFileServiceInter;
import com.farm.template.domain.Template;
import com.farm.template.domain.TemplateDir;
import com.farm.template.domain.TemplateFile;
import com.farm.template.service.TemplateServiceInter;
import com.farm.template.service.TemplatedirServiceInter;
import com.farm.template.service.TemplatefileServiceInter;
import com.farm.wcp.util.ThemesUtil;
import com.farm.web.WebUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

@RequestMapping("/confweb")
@Controller
public class ConfigerWebController extends WebUtils {
	private final static Logger log = Logger.getLogger(ConfigerWebController.class);
	@Resource
	private OutuserServiceInter outUserServiceImpl;
	@Resource
	private UserServiceInter userServiceImpl;
	@Resource
	private WdapFileServiceInter wdapFileServiceImpl;
	@Resource
	private TemplateServiceInter templateServiceImpl;
	@Resource
	private TemplatedirServiceInter templateDirServiceImpl;
	@Resource
	private TemplatefileServiceInter templateFileServiceImpl;
	@Resource
	private ConfigerServiceInter configerServiceImpl;
	@Resource
	private ProjectServiceInter projectServiceImpl;

	/**
	 * 模板管理界面首页
	 * 
	 * @return
	 */
	@RequestMapping("/runTest")
	public ModelAndView runTest(String configerId, String paras, HttpSession session, HttpServletRequest request) {
		ViewMode mode = ViewMode.getInstance();
		try {
			List<Configerform> forms = configerServiceImpl.getForms(configerId, "inner");
			String url = ConfigerFormGenerator.getConfigerModelInstance(configerId).getFormPageUrl();
			String formSubmitUrl = ConfigerFormGenerator.getConfigerModelInstance(configerId).getFormPageSubmitUrl();
			return mode.putAttr("formUrl", url).putAttr("formSubmitUrl", formSubmitUrl).putAttr("forms", forms)
					.putAttr("testparas", paras).returnModelAndView("web-configer-forms/configer-test-form");
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e.getMessage(), e)
					.returnModelAndView(ThemesUtil.getThemePath() + "/simple-500");
		}
	}

	/**
	 * 表单展示（参数模型）
	 * 
	 * @return
	 */
	@RequestMapping("/baseForm")
	public ModelAndView baseForm(String configerid, String activeid, String testparas, HttpSession session,
			HttpServletRequest request) {
		try {
			FormModel formmodel = ConfigerFormGenerator.getConfigerModelInstance(configerid);
			Configer configer = configerServiceImpl.getConfigerEntity(configerid);
			List<ConfigerMetaPara> testParaList = formatTestParas(configerid, testparas);
			Object configerAttr = null;
			if (StringUtils.isNotBlank(activeid)) {
				testParaList = projectServiceImpl.getActiveConfigers(activeid);
				Map<String, Object> configerMap = projectServiceImpl.getActiveConfigerMap(activeid);
				configerAttr = configerMap.get(configer.getCode());
			}
			return formmodel.getFormPageModelAndView(testParaList, configerAttr);
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e.getMessage(), e)
					.returnModelAndView(ThemesUtil.getThemePath() + "/simple-500");
		}
	}

	@RequestMapping("/baseSubmitForm")
	@ResponseBody
	public Map<String, Object> baseSubmitForm(String configerid, String paras, HttpSession session) {
		try {
			ViewMode page = ViewMode.getInstance();
			FormModel formmodel = ConfigerFormGenerator.getConfigerModelInstance(configerid);
			List<ConfigerMetaPara> paraList = FormModelUtils.formatParas(configerid, paras);
			Map<String, Object> configParas = formmodel.submitForm(paraList);

			String json = FormModelUtils.formatObjTojson(configParas);

			return page.putAttr("json", json).returnObjMode();
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e.getMessage(), e).returnObjMode();
		}
	}

	/**
	 * 格式化測試参数
	 * 
	 * @param configerid
	 * @param paras
	 * @return
	 * @throws IOException
	 */
	private List<ConfigerMetaPara> formatTestParas(String configerid, String paras) throws IOException {
		List<Map<String, String>> paraList = FormModelUtils.convertJsonToListOfMaps(paras);
		Map<String, String> paraMap = new HashMap<String, String>();
		for (Map<String, String> node : paraList) {
			paraMap.put(node.get("name"), node.get("val"));
		}
		List<ConfigerMetaPara> metaConfigs = new ArrayList<ConfigerMetaPara>();
		for (Configerform cc : configerServiceImpl.getForms(configerid, "inner")) {
			if (cc.getInnercode() == null) {
				throw new RuntimeException("Innercode is null");
			}
			String jsonStr = paraMap.get(cc.getInnercode());
			if (StringUtils.isNotBlank(jsonStr)) {
				ConfigerMetaPara cm = new ConfigerMetaPara();
				cm.setCode(cc.getCode());
				cm.setJsonString(jsonStr);
				metaConfigs.add(cm);
			}
		}
		return metaConfigs;
	}

}
